package com.read.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.read.common.exception.TokenException;
import com.read.common.response.RespEnum;
import com.read.dto.result.JwtUserDto;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author sh-sunb6
 * @description
 * @date 2019-01-11 15:11
 */
@Component
public class JwtUtil {

    /**
     * @description 创建token
     * @author sh-sunb6
     * @date 2019-01-14 10:43
     */
    public static String createToken(JwtUserDto jUser) {

        String token="";
        Date currentDate = new Date();

        Date expireDate = new Date();
        expireDate.setTime(currentDate.getTime() + Long.parseLong(PropertiesUtil.getProperty("JWT.EXPIRE.TIME")));

        Map<String, Object> headMap = new HashMap<>();
        headMap.put("alg", "HS256");
        headMap.put("typ", "JWT");

        token= JWT.create().withHeader(headMap)
                .withClaim("iss", "BYB")
                .withClaim("aud", "H5")
                .withClaim("userId", jUser.getUserId())
                .withClaim("userName", jUser.getUserName())
                .withClaim("userType", jUser.getUserType())
                .withClaim("userState", jUser.getUserState())
                .withClaim("sex", jUser.getSex())
                .withIssuedAt(currentDate)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(PropertiesUtil.getProperty("JWT.SECRET")));

        return token;
    }

    /**
     * @description 验证token是否合法
     * @author sh-sunb6
     * @date 2019-01-14 10:44
     */
    public static boolean checkToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(PropertiesUtil.getProperty("JWT.SECRET"))).build();
            verifier.verify(token);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * @description 根据token获取用户信息
     * @author sh-sunb6
     * @date 2019-01-14 10:44
     */
    public static JwtUserDto getUserInfo(String token) {
        JwtUserDto jUser = new JwtUserDto();
        DecodedJWT jwt = null;

        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(PropertiesUtil.getProperty("JWT.SECRET"))).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            throw new TokenException(RespEnum.TOKEN_FAILED);
        }

        Map<String, Claim> claims = jwt.getClaims();

        Claim userIdClaim = claims.get("userId");
        Claim userNameClaim = claims.get("userName");
        Claim userTypeClaim = claims.get("userType");
        Claim userStateClaim = claims.get("userState");
        Claim sexClaim = claims.get("sex");

        if (null != userIdClaim)
            jUser.setUserId(userIdClaim.asInt());
        if (null != userNameClaim)
            jUser.setUserName(userNameClaim.asString());
        if (null != userStateClaim)
            jUser.setUserState(userStateClaim.asInt());
        if (null != userTypeClaim)
            jUser.setUserType(userTypeClaim.asInt());
        if (null != sexClaim)
            jUser.setSex(sexClaim.asInt());

        return jUser;
    }

}
